package client;

import java.io.IOException;
import java.net.*;
import java.util.Enumeration;

/**
 * Created by Administrator on 2018/2/3.
 */
public class UdpClient {

    private static ClientParam p =new ClientParam();

    // p.fmsg  "I am UPDClinetA 192.168.85.132"
    public   void conectServer(String fmsg) throws IOException {
        initSocket();
        initPacket(fmsg);
        p.csocket.send(p.pack);
    }


    //接收请求内容
    public  void receive() throws IOException {
        for (;;) {
            getPacket();
            getClientAddress();
            sendB();
        }
    }





    public  void initPacket(String fmsg){
        p.fmsg = fmsg;
        p.sendbuf = p.fmsg.getBytes();
        p.pack = new DatagramPacket(p.sendbuf, p.sendbuf.length, p.target);
    }
    private static void initSocket() throws SocketException {
        p.target = new InetSocketAddress(p.hostname, p.sport);  // 向server发起请求
        p.csocket = new DatagramSocket();
    }


   public void getClientAddress(){
        p.port =  p.packet.getPort();
        p.address =  p.packet.getAddress();
        p.fmsg = "tks";
    }
    public  void getPacket() throws IOException {
        byte[] buf = new byte[1024];
        p.packet = new DatagramPacket(buf, buf.length);
        p.csocket.receive( p.packet);
        p.rmsg = new String( p.packet.getData(), 0,  p.packet.getLength());
        print(p.rmsg);
    }
    public  void print(String msg){
        System.out.println(msg);
    }

    //回复内容
    public  void sendB() throws IOException {
        byte[] sendBuf = p.fmsg.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length,  p.address,  p.port);
        p.csocket.send(sendPacket);
        print("消息发送成功!");

    }


}
